﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Beetle.Web.UI.WebControls;

namespace Beetle.Web.Composite
{
    public class ExtensionCollection<T> : Collection<ExtensionBase> where T : IExtensibleObject<T>
    {
        private T owner;
        private object lockObject = new object();
        public ExtensionCollection(T owner)
        {
            this.owner = owner;
        }

        protected override void ClearItems()
        {
            lock (this.lockObject)
            {
                base.ClearItems();

                ExtensionBase[] array = new ExtensionBase[base.Count];
                base.CopyTo(array, 0);
                base.ClearItems();
                foreach (ExtensionBase extension in array)
                {
                    extension.Detach(this.owner);
                }
            }
        }

        protected override void InsertItem(int index, ExtensionBase item)
        {
            if (item == null)
            {
                return;
            }

            lock (this.lockObject)
            {
                item.Attach(this.owner);
                base.InsertItem(index, item);
            }
        }

        protected override void RemoveItem(int index)
        {
            lock (this.lockObject)
            {
                base.Items[index].Detach(this.owner);
                base.RemoveItem(index);
            }
        }

        protected override void SetItem(int index, ExtensionBase item)
        {
            throw new Exception("ExtensionCollection 不支持SetItem方法");
        }
    }
}
